/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package diepafi;

import model.Playlist;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import model.Song;
import programm.DBmanager;

/**
 *
 * @author Παναγιώτης
 */
public class PlaylistSongEditGUI extends javax.swing.JDialog {
    Playlist playlist = new Playlist(); //η playlist σε περίπτωση επεξεργασίας
    Playlist addPlaylist=new Playlist(); //η playliust που επιστρέφεται για ενημέρωση του πίνακα
    int oldId; //μεταβλητή για το "κράτημα" κωδικού προς επεξεργασία λίστας
    DefaultTableModel model;  //θα χρειαστεί για την επεξεργασία του πίνακα
    DefaultTableModel addModel; //θα το χρειαστούμε για να εισάγουμε νέα τραγούδια στην playlist 

    private static EntityManager em;    //o entity manager
    
    

    // Δημιουργούμε ένα Calendar
    Calendar calendar = Calendar.getInstance();
    // και περνουμε την τρέχουσα ώρα
    Date now = calendar.getTime();
    //περνάμε την τρέχουσα ημερομηνία και ώρα σε μια Timestamp για να ενημερώσουμε
    //το αντίστοιχο πεδίο της playlist (ημερομηνία δημιουργίας/τροποποίησης
    Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());

    /**
     * A return status code - returned if Cancel button has been pressed
     */
    public static final int RET_CANCEL = 0;
    /**
     * A return status code - returned if OK button has been pressed
     */
    public static final int RET_OK = 1;

    /**
     * Creates new form PlaylistSongEditGUI
     * @param parent
     * @param modal
     */
    public PlaylistSongEditGUI(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
         //Ανοίγει την ΒΔ
      DBmanager dbm = new DBmanager(); 
     PlaylistSongEditGUI.em=dbm.getEm();
     
        initComponents();

        // Close the dialog when Esc is pressed
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
        ActionMap actionMap = getRootPane().getActionMap();
        actionMap.put(cancelName, new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                doClose(RET_CANCEL);
            }
        });
    }

    /**
     * @return the return status of this dialog - one of RET_OK or RET_CANCEL
     */
    public int getReturnStatus() {
        return returnStatus;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDialog1 = new javax.swing.JDialog();
        jPanel1 = new javax.swing.JPanel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableSong = new javax.swing.JTable();
        jButtonAddSong = new javax.swing.JButton();
        jButtonDelete = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldTitle = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jEditorPaneDescription = new javax.swing.JEditorPane();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldDate = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabelDuration = new javax.swing.JLabel();

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setTitle("Διαχείριση Λίστας");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.setForeground(new java.awt.Color(240, 240, 240));

        okButton.setBackground(new java.awt.Color(0, 0, 0));
        okButton.setForeground(new java.awt.Color(240, 240, 240));
        okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/floppyNeg.png"))); // NOI18N
        okButton.setText("Αποθήκευση");
        okButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setBackground(new java.awt.Color(0, 0, 0));
        cancelButton.setForeground(new java.awt.Color(240, 240, 240));
        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/cancel.gif"))); // NOI18N
        cancelButton.setText("Άκυρο");
        cancelButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jTableSong.setAutoCreateRowSorter(true);
        jTableSong.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Τίτλος", "Καλλιτέχνης/Συγκρότημα", "Διάρκεια"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableSong.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableSong.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTableSong);

        jButtonAddSong.setBackground(new java.awt.Color(0, 0, 0));
        jButtonAddSong.setForeground(new java.awt.Color(240, 240, 240));
        jButtonAddSong.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/music200.png"))); // NOI18N
        jButtonAddSong.setText("Εισαγωγή");
        jButtonAddSong.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButtonAddSong.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddSongActionPerformed(evt);
            }
        });

        jButtonDelete.setBackground(new java.awt.Color(0, 0, 0));
        jButtonDelete.setForeground(new java.awt.Color(240, 240, 240));
        jButtonDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N
        jButtonDelete.setText("Διαγραφή");
        jButtonDelete.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });

        jPanel2.setBackground(new java.awt.Color(51, 51, 51));
        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 153, 153), new java.awt.Color(204, 204, 204)));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(240, 240, 240));
        jLabel2.setText("Όνομα λίστας:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(240, 240, 240));
        jLabel3.setText("Περιγραφή:");

        jScrollPane2.setViewportView(jEditorPaneDescription);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(240, 240, 240));
        jLabel5.setText("Ημερομηνία δημιουργίας/τροποποίησης:");

        jTextFieldDate.setEditable(false);
        jTextFieldDate.setText(currentTimestamp.toString());

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldTitle)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jTextFieldDate, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jLabel3))
                        .addGap(0, 27, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextFieldTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32))
        );

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(240, 240, 240));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Φόρμα Διαχείρισης Λίστας");

        jLabel6.setForeground(new java.awt.Color(240, 240, 240));
        jLabel6.setText("Συνολική διάρκεια:");

        jLabelDuration.setForeground(new java.awt.Color(240, 240, 240));
        jLabelDuration.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabelDuration.setText("0h 0m 0s");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabelDuration, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonAddSong)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(okButton)
                        .addGap(18, 18, 18)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelDuration)
                            .addComponent(jLabel6)))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAddSong)
                    .addComponent(jButtonDelete)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getRootPane().setDefaultButton(okButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        //τροποποίηση του πίνακα με τα νέα δεδομένα
        //δημιουργία μιας playlist  με τιμές των πεδίων του τα περιεχόμενα της φόρμας
        Playlist playlist = new Playlist();
        String listTitle = jTextFieldTitle.getText();
        String listDescription = jEditorPaneDescription.getText();
      
        //παίρνουμε την στιγμή αποθήκευσης   
        Timestamp saveTimestamp = new java.sql.Timestamp(now.getTime());
        Date created= saveTimestamp;
      
        //έλεγχος εγκυρότητας δεδομένων
        if(listTitle.length() < 1 || listTitle.length()>50){
            JOptionPane.showMessageDialog(this , "Όχι κενό και μέχρι 50 χαρακτήρες", "Τίτλος", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(listDescription.length() > 250){
            JOptionPane.showMessageDialog(this , "Μέχρι 250 χαρακτήρες", "Περιγραφή", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if(listDescription.length() > 250){
            JOptionPane.showMessageDialog(this , "Μέχρι 250 χαρακτήρες", "Περιγραφή", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        //ελέγχουμε την επαρκή διάρκεια τραγουδιών    
        model=(DefaultTableModel) jTableSong.getModel(); 
        int rowCount=jTableSong.getRowCount(); 
        int duration=0;
        for(int i=0;i<rowCount;i++) {
            duration+=(int) jTableSong.getValueAt(i, 2);
        }
        
        if(duration < 1800){
            JOptionPane.showMessageDialog(this , "Ελάχιστη διάρκεια playlist 30 λεπτά.", "Διάρκεια τραγουδιών playlist", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        playlist.setListTitle(listTitle);
        playlist.setDescription(listDescription);
        playlist.setCreation(created);
        
        //κρατάμε τα τραγούδια που βρίσκονται υπο δημιουργία/επεξεργασία playlist
        List<Song> songs=new ArrayList();
        Song addSong=new Song();

        for (int i=0; i<rowCount;i++) {
          try {  
            try {    
            Query q1=em.createQuery("SELECT s FROM Song s WHERE s.songTitle=\""+jTableSong.getValueAt(i, 0)+"\" AND s.albumId.artistId.artisticName=\""+jTableSong.getValueAt(i, 1)+"\" AND s.duration="+jTableSong.getValueAt(i, 2), Song.class);
                addSong=(Song) q1.getResultList().get(0); 
                songs.add(addSong);
            } catch (ArrayIndexOutOfBoundsException ae) {
                     Query q1=em.createQuery("SELECT s FROM Song s WHERE s.songTitle=\""+jTableSong.getValueAt(i, 0)+"\" AND s.albumId.groupId.groupName=\""+jTableSong.getValueAt(i, 1)+"\" AND s.duration="+jTableSong.getValueAt(i, 2), Song.class);
                     addSong=(Song) q1.getResultList().get(0); 
                     songs.add(addSong);
            }
          } catch (ArrayIndexOutOfBoundsException ai) {
                JOptionPane.showMessageDialog(this , "Αφαίρεση τραγουδιών που δεν υπάρχουν πια στην βάση", "Μήνυμα", JOptionPane.ERROR_MESSAGE);
          }
        }
        
        
        //κρατάμε όλα τα τραγούδια
        Query q2=em.createQuery("SELECT s FROM Song s", Song.class);
        List<Song> allSongs=new ArrayList();
        allSongs= q2.getResultList();
        
        //αν ο τίτλος του παραθύρου είναι "Δημιουργία" αποθηκεύουμε τη νέα playlist στη βάση
        switch (this.getTitle()) {
            case "Δημιουργία":
                try {
                    em.getTransaction().begin();
                    em.persist(playlist);
                    em.getTransaction().commit();
                    addPlaylist=playlist; //κρατάμε την νέα playlist για να ενημερώσουμε τον πίνακα με τις λίστες τραγουδιών
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this , "Υπάρχη ήδη λίστα με αυτό το όνομα", "Μήνυμα", JOptionPane.ERROR_MESSAGE);
                    // em.getTransaction().rollback();
                    return;
                }
                //προσθέτουμε τα τραγούδια στην λίστα (και αντίστροφα καθώς έχουμε σχέση n-m)
                Query q3=em.createQuery("SELECT pl FROM Playlist pl WHERE pl.listId=(SELECT MAX(p.listId) FROM Playlist p)", Playlist.class);
                Playlist lastList=(Playlist) q3.getResultList().get(0); //παίρνουμε την playlist που μόλις αποθηκεύσαμε
                Playlist setSongList=em.find(Playlist.class, lastList.getListId());
                em.getTransaction().begin();
                for(Song s: allSongs) {
                    boolean flag=false;
            for (Song plSong : songs) {
                if(Objects.equals(s.getSongId(), plSong.getSongId())) flag=true;
            }
                    if(flag) {
                        Song sng =em.find(Song.class, s.getSongId());
                        sng.getPlaylistCollection().add(setSongList);
                }
                }   setSongList.setSongCollection(songs);
                em.flush();
                em.clear();
                em.getTransaction().commit();
                
                //αλλιώς, αν είναι "Επεξεργασία" αναζητούμε την εγγραφή στον πίνακα
                //και τροποποιούμε τα πεδία της
                break;
            case "Επεξεργασία":
                Playlist editedList=em.find(Playlist.class, oldId); //στην oldId έχουμε αποθηκεύσει την id του επιλεγμένου γκρουπ
                em.getTransaction().begin();
                //επικαιροποίηση της λίστας τραγουδιών και playlist αντίστοιχα
                for(Song s: allSongs) {
                    boolean flag=false;
            for (Song plSong : songs) {
                if(Objects.equals(s.getSongId(), plSong.getSongId())) flag=true;
            }
                    if(!flag) {
                        s.getPlaylistCollection().remove(editedList);
                        Song sng =em.find(Song.class, s.getSongId());
                        sng.setPlaylistCollection(s.getPlaylistCollection());
                    } else {
                        flag = false;
                        for (Playlist p : s.getPlaylistCollection()) {
                            if(Objects.equals(p.getListId(), editedList.getListId())) flag=true;
                        }
                        if(!flag) {
                            s.getPlaylistCollection().add(editedList);
                            Song sng =em.find(Song.class, s.getSongId());
                            sng.setPlaylistCollection(s.getPlaylistCollection());
                        }
                    }
                }   editedList.setListTitle(listTitle);
                editedList.setDescription(listDescription);
                editedList.setCreation(created);
                editedList.setSongCollection(songs);
                addPlaylist=editedList; //κρατάμε την επεξεργασμένη playlist για να εμφανίσουμε τα νέα στοιχεία στον πίνακα λιστών
                em.flush();
                em.clear();
                em.getTransaction().commit();
                break;
        }      
        
        doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * Closes the dialog
     */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
       model=(DefaultTableModel) jTableSong.getModel();
       int row=jTableSong.getSelectedRow();
       if(row==-1) { //μήνυμα σε περίπτωση μη επιλεγμένης γραμμής
           JOptionPane.showMessageDialog(this, "Δεν επιλέξατε τραγούδι ή δεν υπάρχουν τραγούδια στην λίστα");
       } else {
            model.removeRow(row);
       }
       jLabelDuration.setText(duration()); //μετά από διαγραφή επαναϋπολογίζουμε την διάρκεια της playlist
    }//GEN-LAST:event_jButtonDeleteActionPerformed

    private void jButtonAddSongActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddSongActionPerformed
        SongToPlaylistGUI selectSong=new SongToPlaylistGUI(this, true); //ανοίγει την φόρμα που περιέχει τα τραγούδια
        selectSong.setLocation(this.getWidth()+this.getX()-selectSong.getWidth(), this.getY());
        selectSong.setVisible(true);
        if(selectSong.getReturnStatus()==1) {  //αν βγούμε με αποδοχή, προσθέτη το τραγούδι στον πίνακα
            String[] selection=selectSong.getSelection(); //περνάει σε έναν πίνακα String τα στοιχεία του τραγουδιού που θέλουμε να εμφανίζονται
            model=(DefaultTableModel) jTableSong.getModel();
          if(jTableSong.getRowCount()<1) {
                model.addRow(new Object[] {selection[0], selection[1], Integer.parseInt(selection[2])});
            } else {
                boolean flag=true;
                for(int i=0; i<jTableSong.getRowCount();i++) {
                   if(model.getValueAt(i, 0).equals(selection[0]) && model.getValueAt(i, 1).equals(selection[1]))
                       flag=false;
                }
                if(flag) {
                    model.addRow(new Object[] {selection[0], selection[1], Integer.parseInt(selection[2])});
                } else {
                    JOptionPane.showMessageDialog(this , "Υπάρχει ήδη στην playlist", "Λίστα Τραγουδιών", JOptionPane.ERROR_MESSAGE);
                }
            }
          jLabelDuration.setText(duration()); //ενημερώνουμε την διάρκεια της playlist
        } 
    }//GEN-LAST:event_jButtonAddSongActionPerformed

    private void jTextFieldTitleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldTitleActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldTitleActionPerformed
    
    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongEditGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongEditGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongEditGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongEditGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(() -> {
            PlaylistSongEditGUI dialog = new PlaylistSongEditGUI(new javax.swing.JFrame(), true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);
        });
    }
    
    //η playlist που θα εμφανίσουμε
    public void setPlaylist(Playlist playlist) {
        this.playlist=playlist;
    }
    
    //μέθοδος για το "γέμισμα" των πεδίων της φόρμας με τα στοιχεία της playlist
    public void setFields() {
            oldId=playlist.getListId();
            jTextFieldTitle.setText(playlist.getListTitle());
            jEditorPaneDescription.setText(playlist.getDescription());
            int year=playlist.getCreation().getYear()+1900;
            jTextFieldDate.setText(playlist.getCreation().getDate()+" / "+playlist.getCreation().getMonth()+" / "+year+",  "+playlist.getCreation().getHours()+":"+playlist.getCreation().getMinutes());
     
            //γεμίζουμε τον πίνακα με τα τραγούδια της λίστας
            String singerName= new String(); //αποθηκεύει το όνομα καλλιτέχνη / συγκροτήματος, ανάλογα με το τραγούδι
            for(Song song: playlist.getSongCollection()) {
                try {
                    singerName= song.getAlbumId().getGroupId().getGroupName();
                } catch(NullPointerException n) {
                    singerName= song.getAlbumId().getArtistId().getArtisticName();
                }
  
            model=(DefaultTableModel) jTableSong.getModel();            
            model.addRow(new Object[] {song.getSongTitle(), singerName, song.getDuration()});
          }
           jLabelDuration.setText(duration()); //υπολογίζουμε την διάρκεια της playlist 
                
    }
    
   
    //υπολογίζει την χρονική διάρκεια της playlist
    public String duration() {
        model=(DefaultTableModel) jTableSong.getModel(); 
        int rowCount=jTableSong.getRowCount(); 
        int duration=0;
        for(int i=0;i<rowCount;i++) {
            duration+=(int) jTableSong.getValueAt(i, 2);
        }
        int h= duration/3600;
        int m=(duration-h*3600)/60;
        int s=duration-h*3600-m*60;
        
        String dur= h+"h "+m+"m "+s+"s";
        return dur;
    }
    
    //επιστρέφη την playlist για να επιμερωθεί ο πίνακας playlist
    public Playlist getAddPlaylist() {
        return addPlaylist;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton jButtonAddSong;
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JEditorPane jEditorPaneDescription;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelDuration;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTableSong;
    private javax.swing.JTextField jTextFieldDate;
    private javax.swing.JTextField jTextFieldTitle;
    private javax.swing.JButton okButton;
    // End of variables declaration//GEN-END:variables

    
    private int returnStatus = RET_CANCEL;
    
}
